package com.wechat.page.comps;

import java.util.List;

import com.swak.fx.support.ui.UIImage;
import com.swak.fx.support.ui.UITextFlow;
import com.swak.utils.Lists;
import com.wechat.face.Face;
import com.wechat.face.Faces;

import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;

/**
 * 文本处理
 * 
 * @author 618lf
 */
public interface TextComp {

	/**
	 * 处理UITextFlow 的显示问题
	 * 
	 * @param flow
	 * @param content
	 */
	default void buildTextContent(UITextFlow flow, String content) {
		this.buildTextContent(flow, content, false);
	}

	/**
	 * 处理UITextFlow 的显示问题
	 * 
	 * @param flow
	 * @param content
	 */
	default void buildTextContent(UITextFlow flow, String content, boolean useDraft) {
		flow.getChildren().clear();
		List<Node> nodes = this.buildTextContent(content);
		if (useDraft) {
			nodes.add(0, this.buildText("[草稿]"));
		}
		for (int i = 0; i < nodes.size(); i++) {
			Node node = nodes.get(i);
			flow.getChildren().add(node);
			node.getStyleClass().add((useDraft && i == 0) ? "draft-text" : "text");
			GridPane.setColumnIndex(node, i);
			GridPane.setValignment(node, VPos.CENTER);
			GridPane.setVgrow(node, Priority.ALWAYS);
		}
		this.ellipsis(flow);
	}

	default void ellipsis(UITextFlow flow) {
		flow.ellipsis();
	}

	/**
	 * 处理 内容中包含图片 的显示问题
	 * 
	 * @param content
	 */
	default List<Node> buildTextContent(String content) {
		List<Object> texts = Faces.parseString(content);
		List<Node> nodes = Lists.newArrayList();
		for (Object text : texts) {
			if (text instanceof String) {
				char[] chars = ((String) text).toCharArray();
				for (char c : chars) {
					Node node = this.buildLabel(Character.toString(c));
					nodes.add(node);
				}
			} else if (text instanceof Face) {
				Node node = this.buildImage((Face) text);
				nodes.add(node);
			}
		}
		return nodes;
	}

	default Text buildText(String text) {
		Text textNode = new Text();
		textNode.setText(text);
		textNode.setTextAlignment(TextAlignment.JUSTIFY);
		return textNode;
	}

	default Text buildLabel(String text) {
		Text textNode = new Text();
		textNode.setText(text);
		textNode.setTextAlignment(TextAlignment.JUSTIFY);
		return textNode;
	}

	default Node buildImage(Face face) {
		UIImage image = new UIImage();
		image.setPrefSize(18, 18);
		image.image(face.getRealPath());
		return image;
	}
}
